package com.solution.admin.finance.wallet.controller;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.aliyun.oss.common.utils.DateUtil;
import com.solution.admin.finance.wallet.entity.WalletEntity;
import com.solution.admin.finance.wallet.entity.WalletFlowEntity;
import com.solution.admin.finance.wallet.entity.WalletWithdrawEntity;
import com.solution.admin.finance.wallet.service.WalletFlowService;
import com.solution.admin.finance.wallet.service.WalletService;
import com.solution.admin.finance.wallet.service.WalletWithdrawService;
import com.solution.common.controller.BaseController;
import com.solution.common.page.JSONGrid;
import com.solution.common.page.PageBean;
import com.solution.common.page.PageParam;

/**
 * 客户钱包提现web控制层
 * @author lufer
 * @date 2018-05-04 16:52:30
 */
@RequestMapping("/walletWithdraw")
@Controller
public class WalletWithdrawController extends BaseController {

	private Logger logger = LoggerFactory.getLogger(WalletWithdrawController.class);

	@Autowired
	private WalletWithdrawService walletWithdrawService;
	@Autowired
	private WalletService walletService;
	@Autowired
	private WalletFlowService walletFlowService;
	
	/**
	 * 跳转客户钱包提现查询页面
	 * @param WalletWithdraw 接收界面查询条件参数
	 * @param request 请求对象
	 * @return 返回对应的页面视图
	 * @author lufer
 	 * @date 2018-05-04 16:52:30
	 */
	@RequestMapping("/toListWalletWithdrawPage")
	public String toListWalletWithdrawPage(HttpServletRequest request) {
		return "withdraw/walletWithdraw_list";
	}

	/**
	 * 分页查询客户钱包提现列表
	 * @param walletWithdraw 接收界面查询条件参数
	 * @param request 请求对象
	 * @return 返回对应的页面视图
	 * @author lufer
 	 * @date 2018-05-04 16:52:30
	 */
	@RequestMapping("/listWalletWithdrawPage")
	@ResponseBody
	public JSONGrid listWalletWithdrawPage(HttpServletRequest request){
		int pageNum=Integer.parseInt(request.getParameter("page").toString());
		int numPerPage=Integer.parseInt(request.getParameter("rows").toString());
		PageParam pageParam = super.getPageParam(request);
		pageParam.setPageNum(pageNum);
		pageParam.setNumPerPage(numPerPage);
		
		//查询条件（客户姓名）
		String customerName = request.getParameter("customerName");
		//查询条件（申请开始时间）
		String beginTime = request.getParameter("beginTime");
		//查询条件（申请结束时间）
		String endTime = request.getParameter("endTime");
		//查询条件（状态）
		String withdrawStatus = request.getParameter("withdrawStatus");
		//封装查询条件
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("customerName", customerName);
		paramMap.put("beginTime", beginTime);
		paramMap.put("endTime", endTime);
		paramMap.put("withdrawStatus", withdrawStatus);
		
		try {
			PageBean pageBean = walletWithdrawService.listWalletWithdrawPage(pageParam, paramMap);
			return new JSONGrid(pageBean.getRecordList(),pageBean.getTotalCount());
		} catch (Exception e) {
			handleException("分页查询客户钱包提现失败", logger, e);
		}
		return new JSONGrid();
	}
	
	
	/**
	 * 跳转提现处理界面
	 * @return string 跳转页面路径
	 * @author lufer
 	 * @date 2018-05-04 16:52:30
	 */
	@RequestMapping("/toAuditWalletWithdraw")
	public String toAddWalletWithdraw(HttpServletRequest request) {
		//获取提现申请id
		long id = Long.valueOf(request.getParameter("id"));
		//根据id获取提现申请信息
		WalletWithdrawEntity walletWithdrawEntity = walletWithdrawService.getWalletWithdrawById(id);
		if(null != walletWithdrawEntity){
			request.setAttribute("withdraw", walletWithdrawEntity);
		}
		return "withdraw/walletWithdraw_audit";
	}

	/**
	 * 处理提现申请
	 * 作者：lufer
	 * 时间：2018年6月11日 下午8:31:46
	 * @param request
	 * @param walletWithdrawEntity
	 * @return
	 */
	@RequestMapping("/auditWalletWithdraw")
	@ResponseBody
	public Map<String, Object> auditWalletWithdraw(HttpServletRequest request, WalletWithdrawEntity walletWithdrawEntity) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			String id = request.getParameter("id");
			walletWithdrawEntity.setId(Long.valueOf(id));
			walletWithdrawEntity.setPayUserId(this.getUserId().intValue());
			int	result = walletWithdrawService.updateWalletWithdraw(walletWithdrawEntity);
			
			/**
			 * 处理提现
			 * 如果是审核通过，则需要把账户此次提现金额从账户中提现中金额减去；
			 * 如果是驳回，则需要把账户中此次提现金额从提现中返还至账号可提现余额中；同时要生产提现财务流水记录
			 */
			if(result>0){
				/***************查询当前登录客户财富汇总信息****************/
				Map<String, Object> paramMap = new HashMap<String, Object>();
				WalletEntity wallet = null;
				//封装查询参数
				paramMap.put("customerId", walletWithdrawEntity.getCustomerId());
				//查询当前登录客户的财富
				List<WalletEntity> walletList = walletService.listWallet(paramMap);
				//当前账号余额
				if(null != walletList){
					Iterator<WalletEntity> it = walletList.iterator();
					if(it.hasNext()){
						wallet = (WalletEntity)it.next();
					}
				}
				//可提现余额
				BigDecimal getableMoney = wallet.getGetableMoney();
				//提现中金额
				BigDecimal getingMoney = wallet.getGetingMoney();
				//如果是审核通过，则需要把账户此次提现金额从账户中提现中金额减去
				if(walletWithdrawEntity.getWithdrawStatus()==2){
					//提现中金额减去此次提现金额
					wallet.setGetingMoney((getingMoney.subtract(walletWithdrawEntity.getWithdrawMoney())).setScale(2));
					//修改账户
					walletService.updateWallet(wallet);
					
				}else if(walletWithdrawEntity.getWithdrawStatus()==3){//如果是驳回，则需要把账户中此次提现金额从提现中返还至账号可提现余额中
					//可提现金额加上此次提现金额
					wallet.setGetableMoney((getableMoney.add(walletWithdrawEntity.getWithdrawMoney())).setScale(2));
					//提现中金额减去此次提现金额
					wallet.setGetingMoney((getingMoney.subtract(walletWithdrawEntity.getWithdrawMoney())).setScale(2));
					//修改账户
					int rs = walletService.updateWallet(wallet);
					/****************************账户余额变动则生产客户流水记录*************************/
					if(rs>0){
						WalletFlowEntity flowEntity = new WalletFlowEntity();
						//封装流水记录数据
						flowEntity.setCustomerId(walletWithdrawEntity.getCustomerId());//客户ID
						flowEntity.setFlowType("4");//类型为提现驳回退款
						flowEntity.setPayType("1");//收入
						flowEntity.setInMoney(walletWithdrawEntity.getWithdrawMoney());//收入金额
						flowEntity.setBalanceMoney((getableMoney.add(walletWithdrawEntity.getWithdrawMoney())).setScale(2));//当前账户余额
						flowEntity.setBillId(walletWithdrawEntity.getId().intValue());//提现单据ID
						//执行添加账号财务流水
						walletFlowService.saveWalletFlow(flowEntity);
					}
				}
			}
			resultMap.put("code", result);
		} catch (Exception e) {
			handleException("处理提现失败", logger, e);
		}
		return resultMap;
	}
	
	/**
	 * 跳转到查看详情页面
	 * 作者：lufer
	 * 时间：2018年6月12日 下午4:27:41
	 * @param request
	 * @return
	 */
	@RequestMapping("/toDetailWalletWithdraw")
	public String toDetailWalletWithdraw(HttpServletRequest request) {
		//获取提现申请id
		long id = Long.valueOf(request.getParameter("id"));
		//根据id获取提现申请信息
		WalletWithdrawEntity walletWithdrawEntity = walletWithdrawService.getWalletWithdrawById(id);
		if(null != walletWithdrawEntity){
			request.setAttribute("withdraw", walletWithdrawEntity);
		}
		return "withdraw/walletWithdraw_detail";
	}
	
}
